import auth from '@/utils/auth';
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/',
      component: () => import('@/views/home/index.vue'),
      children: [
        {
          path: '',
          component: () => import('@/views/home/index.vue')
        },
        {
          path: 'article',
          component: () => import('@/views/article/index.vue')
        },
        {
          path: 'publish/:id?',
          component: () => import('@/views/publish/index.vue')
        }
      ]
    }
  ],
});

router.beforeEach((to, from, next) => {
  const token = auth.getToken();
  if (to.path !== '/login' && !token) return next('/login');
  next();
});

export default router;
